//
//  Userinfo.m
//  SSC
//
//  Created by 红沙尘 on 17/6/19.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "Userinfo.h"

@interface Userinfo ()
{
    NSString *_uid;
    NSString *_username;
    NSString *_password;
    NSString *_token;
    NSString *_money;
}
@end

@implementation Userinfo



- (void)dealloc {
    NSLog(@"%@ dealloc",self);
    
}

static Userinfo *userinfo = nil;

+ (Userinfo *)standardUserinfo {
    
    if (!userinfo)
    {
        userinfo = [[Userinfo alloc] init];
    }
    return userinfo;
}

- (id)init {
    
    self = [super init];
    
    if (self) {
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *dict = [defaults valueForKey:@"SSC"];
        
        _uid      = [[NSString safeString:dict[@"uid"]] copy];
        _username = [[NSString safeString:dict[@"username"]] copy];
        _password = [[NSString safeString:dict[@"password"]] copy];
        _token    = [[NSString safeString:dict[@"token"]] copy];
    }
    
    return self;
}

- (BOOL)saveUserinfoWithUid:(NSString *)uid
                   username:(NSString *)username
                   password:(NSString *)password
                      token:(NSString *)token {
    
    if (uid.length == 0 || username.length == 0 || password.length == 0 || token.length == 0) {
        return NO;
    }
    
    _uid      = [uid copy];
    _username = [username copy];
    _password = [password copy];
    _token    = [token copy];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSDictionary *dict = @{@"uid":_uid,
                           @"username":_username,
                           @"password":_password,
                           @"token":_token,};
    
    [defaults setObject:dict forKey:@"SSC"];
    
    [defaults synchronize];
    
    return [self isLogin];
}

- (BOOL)isLogin {
    if (_uid.length == 0 || _username.length == 0 || _password.length == 0 || _token.length == 0) {
        return NO;
    }
    return YES;
}

- (void)updateMoney:(NSString *)money {
    _money = [money copy];
}

- (void)userMoney:(void (^)(NSString *money))complete {
    
    [SSCRequest queryUserAmountSuccess:^(NSDictionary *responseObject) {
        
        NSDictionary *data = responseObject[@"data"];
        
        [self updateMoney:[NSString safeString:data[@"amount"]]];
        
        complete(_money);
    } fail:^(NSError *error) {
        
    }];
}

- (void)destory {
    
    [self.timer invalidate];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"SSC"];
    
    
    userinfo = nil;
}

@end
